const dayjs = require('dayjs')
const db = require('../config/dbConfig')
class File{
    constructor(fileInfo) {
        this.fileInfo = fileInfo
    }
    async deleteFile(){
        const {id} = this.fileInfo
        const deleteFileSql = "DELETE FROM file WHERE id = ?";
        const Info = await db.execute(deleteFileSql, [id]);
        return {
            code: 200,
            msg: "删除成功",
            data: {},
        };
    }
    async getFileList(){
        const {userRole,userId, query} = this.fileInfo
        const{fileName, fileType, page=1, pageSize=10} = query
        const conditions = [];
        const params = [];
        if (fileName) {
            conditions.push("fileName LIKE ?");
            params.push(`%${fileName}%`);
        }
        if (fileType) {
            conditions.push("fileType = ?");
            params.push(fileType);
        }
        // 权限判定 != admin 搜索userId
        if (userRole!== 'admin') {
            conditions.push("userId = ?");
            params.push(userId);
        }

        let whereClause = conditions.length > 0? `WHERE ${conditions.join(' AND ')}` : '';
        const getFileListSql = `SELECT * FROM file ${whereClause} ORDER BY id DESC LIMIT ?,?`;
        params.push((page - 1) * pageSize, Number(pageSize));
        try {
            const [Info] = await db.execute(this.getFinalSql(getFileListSql, params));
            return {
                code: 200,
                msg: "查询成功",
                data: {
                    list: Info,
                    total: Info.length
                },
            };
        } catch (err) {
            return {
                code: 500,
                msg: "查询失败",
                data: {}
            };
        }
    }
    getFinalSql(sql, params) {
        let index = 0;
        return sql.replace(/\?/g, () => {
            const param = params[index++];
            if (typeof param === 'string') {
                return `'${param.replace(/'/g, "\\'")}'`;
            }
            return param;
        });
    }
    async uploadFile(){
        const {userId, fileName,fileSize,fileType,fileUrl} = this.fileInfo
        console.log('userId, fileName,fileSize,fileType,fileUrl',userId, fileName,fileSize,fileType,fileUrl)
        const createTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
        const addFileSql = "INSERT INTO file ( userId,fileName,fileSize,fileType,fileUrl, createTime) VALUES ( ?,?, ?, ?, ?,?)";
        const Info = await db.execute(addFileSql, [
            fileName,fileSize,fileType,fileUrl,createTime,
        ]);
        return {
            code: 200,
            msg: "上传成功",
            data: {},
        };
    }
    static downloadFile(id) {
        const sql = "SELECT * FROM file WHERE id = ?";
        return db.execute(sql, [id]);
    }
}
module.exports = File
